import { View, Text } from '@tarojs/components'
import { ArrowRight, CdnImage, FloatAddButton } from '@/ui-components'
import Taro from '@tarojs/taro'
import to from 'await-to-js'
import { getTreasuryTaskList } from '@/network/treasury'
import { useAppDispatch, useAppSelector } from '@/store/hooks'
import { useMount } from '@/hooks'
import { TreasuryTask, setTreasuryTaskList } from '@/store/treasurySlice'
import Card from '@/ui-components/card'
import { TaskTypeImage } from '@/constants'
import dayjs from 'dayjs'
import { map } from 'lodash'
import './index.scss'

interface TreasuryTaskItemProps {
  task: TreasuryTask
  onClick: () => void
}

const TreasuryTaskItem = ({ task, onClick }: TreasuryTaskItemProps) => {
  return (
    <Card padding onClick={onClick}>
      <View className='row-between-center'>
        <View className='row-start-stretch flex-1'>
          <CdnImage src={TaskTypeImage[task.type]} className='image-160 border-radius-small' />
          <View className='column-between-start flex-1 mh-medium'>
            <View className='text-title'>{task.name}</View>
            <View className='text-normal'>任务奖励：<Text className='success'>{task.score}</Text>积分</View>
            <View className='text-normal'><Text className='warning'>{`${dayjs(task.deadline).format('YYYY/MM/DD HH:mm:ss')}`}</Text> 到期</View>
          </View>
        </View>
        <ArrowRight />
      </View>
    </Card>
  )

}

export default function TreasuryTaskPage() {
  const treasuryId = useAppSelector(state => state.treasury.userTreasury.treasuryId)
  const taskList = useAppSelector(state => state.treasury.taskList)
  const dispatch = useAppDispatch()

  useMount(async () => {
    const [err, taskList] = await to(getTreasuryTaskList(treasuryId, { hideLoading: true }))
    if (err) return
    dispatch(setTreasuryTaskList(taskList))
  })

  return (
    <View className='treasury-task'>
      <View className='pv-medium bg-primary row-start-center'>
        <View className='text-center flex-1 text-primary border-right'>发布任务</View>
        <View className='text-center flex-1 text-primary'>提交记录</View>
      </View>
      {
        map(taskList, (task: TreasuryTask) => (
          <TreasuryTaskItem
            key={task.taskId}
            task={task}
            onClick={() => Taro.navigateTo({url: `/subpages/treasury/task/detail/index?treasuryTaskId=${task.taskId}`})}
          />
        ))
      }
      <FloatAddButton
        onClick={() => {
          Taro.navigateTo({
            url: '/subpages/treasury/task/create/index'
          })
        }}
      />
    </View>
  )
}
